﻿using Dapper;
using Oracle.ManagedDataAccess.Client;
using Serilog;
using SyncWayBill.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using Volo.Abp.DependencyInjection;

namespace SyncWayBill
{
    public class SyncMadanStatus : ITransientDependency
    {
        private ConnectionService ConnectionService;
        public SyncMadanStatus(ConnectionService connectionService)
        {
            ConnectionService = connectionService;
        }
        public void Unloading()
        {
            using (var conn = ConnectionService.GetConnection())
            {
                conn.Open();
                var sql = @"select*from ( SELECT A.ID               AS AID,
                                   A.YW_YD_ID       AS tmsWaybillId,
                                   D.DELIVERY_CODE    AS CODE,
                                   nvl(SUM(DS.SIGNER_NUM),0) AS weight
                            FROM YDGL_DELIVERY_NOTE D
                                     JOIN YDGL_ASSEMBLE_MESSAGE A
                                          ON D.ID = A.DELIVERY_ID
                                     JOIN YDGL_DELIVERY_NOTE_SUB DS ON A.ID = DS.ASSEMBLE_ID
                            WHERE D.STATUS = '21'
                              AND IS_SEND_YWLODIING = 1
                              AND IS_SEND_UNLOADING != 1
                              and A.YW_YD_ID >0
                            GROUP BY A.ID, A.YW_YD_ID,D.DELIVERY_CODE) where rownum <=50";
                var result = SqlMapper.Query<Unloading>(conn, sql);
                foreach (var item in result)
                {
                    item.ids = conn.Query<string>(this.getFilePathSql(), new { aid = item.AID }).ToList();
                    if (item.ids.Count == 0)
                    {
                        item.ids = new List<string> { "码单.jpg" };
                    }
                    var client = new HttpClient();
                    var parameter = Newtonsoft.Json.JsonConvert.SerializeObject(item);
                    var sw = System.Diagnostics.Stopwatch.StartNew();
                    //HttpContent httpContent = new StringContent(parameter);
                    //httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                    //var response = client.PostAsync(ConnectionService.GetUnloading(), httpContent).Result;
                    string responeStr = HttpHelpr.Post(ConnectionService.GetUnloading(), parameter);
                    sw.Stop();
                   // var responeStr = response.Content.ReadAsStringAsync().Result;
                    //var responeResult = Newtonsoft.Json.JsonConvert.DeserializeObject<YWResult<object>>(responeStr);
                    string updateSql = "UPDATE YDGL_ASSEMBLE_MESSAGE SET IS_SEND_UNLOADING=1 WHERE ID =:AID";
                    var insertSql = @"INSERT INTO YDGL_WAYBILL_SYNC (CODE, PARMAETERS, YW_RESULT, STATUS, CREATE_TIME, SEND_STATUS, SEND_COUNT_TIME, SEND_URL, AM_ID)
                                        VALUES (:CODE, :PARMAETERS,:YW_RESULT,:STATUS, :CREATE_TIME, :SEND_STATUS, :SEND_COUNT_TIME, :SEND_URL, :AM_ID)";
                    var way = new YdglWaybillSync()
                    {
                        CODE = item.CODE,
                        PARMAETERS = parameter,
                        YW_RESULT = responeStr,
                        STATUS = 3,
                        CREATE_TIME = DateTime.Now.ToString(),
                        SEND_STATUS = 1,
                        SEND_COUNT_TIME = sw.ElapsedMilliseconds,
                        SEND_URL = ConnectionService.GetUnloading(),
                        AM_ID = item.AID
                    };
                    try
                    {

                        IDbTransaction transaction = conn.BeginTransaction();
                        conn.Execute(updateSql, new { item.AID }, transaction, null, null);
                        conn.Execute(insertSql, new
                        {
                            way.CODE,
                            way.PARMAETERS,
                            way.YW_RESULT,
                            way.STATUS,
                            way.CREATE_TIME,
                            way.SEND_STATUS,
                            way.SEND_COUNT_TIME,
                            way.SEND_URL,
                            way.AM_ID
                        }, transaction, null, null);
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        Log.Logger.Error(e, e.Message);
                        conn.Execute(insertSql, new
                        {
                            CODE = item.CODE,
                            PARMAETERS = parameter,
                            YW_RESULT = responeStr,
                            STATUS = 3,
                            CREATE_TIME = DateTime.Now.ToString(),
                            SEND_STATUS = 2,
                            SEND_COUNT_TIME = sw.ElapsedMilliseconds,
                            SEND_URL = ConnectionService.GetUnloading(),
                            AM_ID = item.AID
                        }, null, null);
                        continue;
                    }
                }

            }
        }
        /// <summary>
        /// 获取运单文件sql
        /// </summary>
        /// <returns></returns>
        private string getFilePathSql()
        {
            string sql = @"select concat('https://zhwlapi.pgxcgv.com/file',f.PATH) as path
            from YDGL_DELIVERY_NOTE d
            inner join YDGL_ASSEMBLE_MESSAGE a on d.ID = a.DELIVERY_ID
            inner join YDGL_FILE f on d.ID = f.YDGL_ID
            where (f.YW_TYPE='qrsh' or f.YW_TYPE is null) and a.ID=:aid";
            return sql;
        }
    }
}
